package com.windy.dailynews.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.windy.dailynews.R;
import com.windy.dailynews.model.News;
import com.windy.dailynews.ui.activity.NewsDetailActivity;
import com.windy.slideview.RecyclingPagerAdapter;

import java.util.List;

/**
 * Created by dingfeng on 2016/11/22.
 */
public class TopAdAdapter extends RecyclingPagerAdapter {
    private Context mContext;
    private List<News.Story> mTopList;
    private int size;
    private boolean isInfiniteLoop = false;

    public TopAdAdapter(Context context, List<News.Story> list) {
        this.mContext = context;
        this.size = list.size();
        mTopList = list;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup container) {
        final News.Story story = mTopList.get(getPosition(position));
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_top_ad, null);
            holder.image = (ImageView) convertView.findViewById(R.id.image);
            holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title) ;
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Glide.with(mContext)
                .load(story.getImage())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(holder.image);
        holder.tv_title.setText(story.getTitle());
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, NewsDetailActivity.class);
                intent.putExtra("newsId", story.getId());
                mContext.startActivity(intent);
            }
        });

        return convertView;
    }

    class ViewHolder {
        ImageView image;
        TextView tv_title;
    }

    @Override
    public int getCount() {
        return isInfiniteLoop ? Integer.MAX_VALUE : size;
    }

    // get real position
    private int getPosition(int position) {
        return isInfiniteLoop ? position % size : position;
    }

    public boolean isInfiniteLoop() {
        return isInfiniteLoop;
    }

    /**
     * @param isInfiniteLoop
     */
    public void setInfiniteLoop(boolean isInfiniteLoop) {
        this.isInfiniteLoop = isInfiniteLoop;
    }

}
